package com.jd.threed.线程池聚合Future;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程池聚合Future 的使用
 */
public class ClassDemo51CountDownLanch {

    ExecutorService executorService = Executors.newFixedThreadPool(3);


    public static void main(String[] args) throws InterruptedException {
        ClassDemo51CountDownLanch classDemo51CountDownLanch = new ClassDemo51CountDownLanch();
        System.out.println(classDemo51CountDownLanch.getPries());
    }



    public Set<Integer> getPries() throws InterruptedException {
        Set<Integer> objects = Collections.synchronizedSet(new HashSet<>());

        CountDownLatch countDownLatch = new CountDownLatch(3);
        executorService.submit(new Task(123,objects,countDownLatch));
        executorService.submit(new Task(233,objects,countDownLatch));
        executorService.submit(new Task(234,objects,countDownLatch));
        countDownLatch.await(3, TimeUnit.SECONDS);
        return objects;
    }


    public class Task implements Runnable {

        Integer productId;

        Set<Integer> prices;

        CountDownLatch countDownLatch;

        public Task (Integer productId, Set<Integer> prices,CountDownLatch countDownLatch) {
            this.productId = productId;
            this.prices = prices;
            this.countDownLatch = countDownLatch;
        }


        @Override
        public void run() {
            int price = 0;

            try {
                Thread.sleep((long) (Math.random() *4000));
                price = (int) (Math.random() * 4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            prices.add(price);

            countDownLatch.countDown();
        }
    }



}
